package com.jr.javaproject.rpc;



import com.alibaba.fastjson.JSONObject;
import com.jr.javaproject.Constants;
import com.jr.javaproject.bean.Rpc;
import com.jr.javaproject.request.HttpUtils;

import java.lang.reflect.Type;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:Fangrongxin
 * @email:204271145@qq.com
 * @desc: 该类用于实现通过rpc调用bitcoin core的getbestblockhash功能
 * @datetime:2021/12/22 15:12
 */
public class GetBestBlockHash {
    public String GetBestBlockHash() {
        //准备rpc请求的用户身份信息，及对应的base64
        String author = Constants.BITCOIN_RPC_USER + ":" + Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());

        //请求头的属性设置
        Map<String, String> header = new HashMap<>();
        header.put("ContentType", "application/json");
        header.put("Authorization", "Basic " + authorBase64);

        Map<String, Object> body = new HashMap<>();
        body.put("id", 1001);
        body.put("method", "getbestblockhash");
        body.put("params", null);
        body.put("json_rpc", "2.0");
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        //{"id":1001,"result":"xxx","error":null}
        String result = HttpUtils.post(Constants.BITCOIN_RPC_URL, header, bodyBytes);
        //反序列化，拿到result的值
       Rpc rpc= JSONObject.parseObject(result, Rpc.class);
        return rpc.result;
    }
}